﻿#include <QtWidgets>
#include "mainwindow.h"
#include "graphicsscene.h"
#include "graphicsitem.h"
#include "commands.h"

/*一个仿照qt的demo写的例子，重复画图，然后undoredo来进行撤销操作*/
MainWindow::MainWindow()
{
    m_pUndoStack = new QUndoStack(this);

    createActions();
    createMenus();
    createUndoView();

    m_pScene = new GraphicsScene();
    m_pScene->setSceneRect(QRect(0, 0, 500, 500));
    QGraphicsView *pView = new QGraphicsView(m_pScene);
    setCentralWidget(pView);

    setWindowTitle("UndoRedo");
    resize(700,600);
}

MainWindow::~MainWindow()
{}


void MainWindow::createActions()
{
    m_pAddBoxAction = new QAction("Add Box",this);
    connect(m_pAddBoxAction,SIGNAL(triggered()),this,SLOT(addBox()));

    m_pUndoAction = m_pUndoStack->createUndoAction(this,"Undo");
    m_pRedoAction = m_pUndoStack->createRedoAction(this,"Redo");
}

void MainWindow::createMenus()
{
    m_pEditMenu = menuBar()->addMenu("Edit");
    m_pEditMenu->addAction(m_pUndoAction);
    m_pEditMenu->addAction(m_pRedoAction);

    m_pItemMenu = menuBar()->addMenu("Item");
    m_pItemMenu->addAction(m_pAddBoxAction);
}

void MainWindow::createUndoView()
{
    m_pUndoView = new QUndoView(m_pUndoStack);
    m_pUndoView->setWindowTitle("Command List");
    m_pUndoView->show();
    m_pUndoView->setAttribute(Qt::WA_QuitOnClose, false);
}

//重复画图形
void MainWindow::addBox()
{
    QUndoCommand *addCommand = new Commands(GraphicsItem::Triangle, m_pScene);
    m_pUndoStack->push(addCommand);
}
